<?php

namespace app\api\middleware;

use app\api\annotation\LoginRequired;
use app\api\basic\BaseController;
use app\api\exception\ApiException;
use app\api\logic\WechatUserLogic;
use Closure;
use ReflectionClass;
use ReflectionMethod;
use support\Container;
use support\Request;
//use support\Response;
use Webman\Http\Response;


class LoginAnnotationMiddleware
{
    public function process(Request $request, Closure $next)
    {
     
        $controller = $request->controller;
        // 仅处理 app\api 命名空间下的控制器
        if (!str_starts_with($controller, 'app\\api')) {
            return $next($request);
        }

        $action = $request->action;

        $reflectionClass = new ReflectionClass($controller);
        $reflectionMethod = $reflectionClass->getMethod($action);

        // 先获取方法级别的注解
        $methodAttributes = $reflectionMethod->getAttributes(LoginRequired::class);
        if ($methodAttributes) {
            $loginRequired = $methodAttributes[0]->newInstance()->required;
        } else {
            // 若方法级别无注解，获取类级别的注解
            $classAttributes = $reflectionClass->getAttributes(LoginRequired::class);
            // 若类级别也无注解，默认需要验证
            $loginRequired = $classAttributes ? $classAttributes[0]->newInstance()->required : true;
        }
        $logic = new WechatUserLogic();
        $result = getCurrentInfo();
       // print_r($result);
         $request->userId=0;
         $request->userName='';
         $request->userInfo=[];

        if (!$result && $loginRequired) {
           
             
                throw new ApiException('用户信息读取失败,请重新登录', 401);
        }
        if($result){
          
            $request->userId = $result['id'];
            $request->userName =isset($result['nickname'])? $result['nickname']:$result['username'];
            $request->userInfo = $logic->find($result['id']);
          
        }
      
        // $logic = new WechatUserLogic();
        // $result = getCurrentInfo();
        // if($result) {
        //  $userInfo = $logic->find($result['id']);
        
        //     $request->userInfo = $userInfo;
        //     $request->userId = $result['id'];
        //     $request->userName = $result['nickname'];

        // }
  

        return $next($request);
    }
}